<%@ page import="com.google.appengine.repackaged.org.codehaus.jackson.map.ser.FilterProvider"%>
<%@ page import="com.google.appengine.api.datastore.Query.Filter"%>
<%@ page import="com.google.appengine.api.datastore.Query.FilterOperator"%>
<%@ page import="com.google.appengine.api.datastore.Query.FilterPredicate"%>
<%@ page import="com.google.appengine.api.datastore.*"%>
<%@ page import="com.google.appengine.api.memcache.*"%>
<%@ page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Praktikaportaal | Ettevõtted</title>
</head>
<body>
	<%@ include file="header.jsp"%>
	<div id="content">
		<div class="content-container">
			<%
				// Warm cache.
				MemcacheService mc = MemcacheServiceFactory.getMemcacheService();
				List<Entity> companies = (List<Entity>) mc.get("companies");

				// Cold cache.
				if (companies == null) {
					DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
					Filter statusFilter = new FilterPredicate("status", FilterOperator.EQUAL, "approved");
					Query query = new Query("Company").setFilter(statusFilter).addSort("name", Query.SortDirection.ASCENDING);
					companies = ds.prepare(query).asList(FetchOptions.Builder.withDefaults());
					mc.put("companies", companies);
				}

				if (companies.isEmpty()) {
			%>

			<p>Ühtegi ettevõtet ei ole.</p>

			<%
				} else {
					int i = 1;
					for (Entity c : companies) {
						Long id = (Long) c.getKey().getId();
						String link = "/company?id=" + id.toString();
						String name = (String) c.getProperty("name");
						String description = ((Text) c.getProperty("description")).getValue();
						String field = (String) c.getProperty("field");
						if (i != 1) {
			%>			
			<hr>
			<%
						}
					i++;
			%>

			<h1><a href=<%= link %>><%= name %></a></h1>
			<p><%= field %></p>
			<p><%= description %></p>

			<%
					}
				}
			%>
		</div>
		<%
			if (isAdmin) {
		%>
		<div class="content-container">
			<h1>Lisa Ettevõte</h1>
			<form action="/addcompany" method="post">
				<table>
					<tr>
						<td><label for="title">Nimi: </label></td>
						<td><input id="name" type="text" name="name"></input></td>
					</tr>
					<tr>
						<td><label for="field">Tegevusvaldkond: </label></td>
						<td><input id="field" type="text" name="field"></input></td>
					</tr>
					<tr>
						<td><label for="description">Kirjeldus: </label></td>
						<td><textarea id="description" name="description"></textarea></td>
					</tr>
				</table>
				<input type="submit" value="Salvesta"></input>
			</form>
		</div>

		<%
			}
		%>
	</div>
	<%@ include file="footer.jsp"%>
</body>
</html>